/**
* PHP Backend for M3DMindMap
*/

var PHPBackend = new Class({
    evt: null,

    init: function (evt){
        //console.debug('mapready')
        if(evt) this.evt = evt;

        var aj = new Request({
            url: 'backend.php',
            data: 'action=login',
            onSuccess: function (response){
                //console.log(this.evt)
                if(response!="0"){
                    this.evt.map.logged = true;
                    $('logininfo').set('html',"<hr />You're logged with user: "+response+"<hr />");
                }
            }.bind(this)
        });

        aj.send();

        this.init.bind(this).delay(30000)

    },

    checklogin: function (evt,nextaction) {
        if(!evt.map.logged) {
            var selectLog = new Element ('div').set({
                'html' : '<h2>Login</h2>'
                         +'<button>I already have account...</button><br />'
                         +'<p style="border-top: 1px solid black; border-bottom: 1px solid black;text-align: center"><strong>or</strong></p><h2>Create Account</h2>'
                         +'<p class="msg"></p>'
                         +'<label>Login: </label><input type="text" name="login" /><br />'
                         +'<label>Password: </label><input type="password" name="password" /><br />'
                         +'<label>Confirm password: </label><input type="password" name="password2" /><br />'
                         +'<label>E-mail: </label><input type="text" name="mail" /><br />'
                         +'<button>Send</button>'
                         +'<br /><em>You email is only used to send new password if you forget it, we will not use it to send you ads or spam</em>'
            })

            var sq = SqueezeBox.open(selectLog,{'handler': 'adopt', 'size': {x: 550, y:230} });

            selectLog.getElements("button")[0].addEvent('click', function(){
                //sq.close();
                this.login(evt,nextaction)
            }.bind(this));


            selectLog.getElements("button")[1].addEvent('click', function(){
                var p1 = selectLog.getElements('input[name=password]')[0].value;
                var p2 = selectLog.getElements('input[name=password2]')[0].value;
                var l = selectLog.getElements('input[name=login]')[0].value;
                var m = selectLog.getElements('input[name=mail]')[0].value;
                if(p1 != p2) {
                    selectLog.getElements('.msg')[0].addClass('error').set("html", "Passwords are not identicals").addClass('show');
                }else {
                    new Request({
                        url:'backend.php',
                        method: 'post',
                        data: 'action=createaccount&login='+l+'&password='+p1+'&mail='+m,
                        onSuccess: function (response) {
                            if (response==1) {
                                evt.map.logged = true;
                                if (nextaction == "open") this._open(evt);
                                if (nextaction == "save") this._save(evt);
                            }else{
                                selectLog.getElements('.msg')[0].addClass('error').set("html", response).addClass('show');
                            }
                        }.bind(this)
                    }).send();
                }
            }.bind(this))
        }else {
            if (nextaction == "open") this._open(evt);
            if (nextaction == "save") this._save(evt);
        }
    },

    login: function (evt,nextaction){
        var login = new Element('div').set({
            'html': '<h2>Please login with you identifiers</h2><br /><br />'+
            '<p class="msg"></p>'+
            '<label>Login</label><input name="login" type="text" /><br />'+
            '<label>Password</label><input name="pwd" type="password" /><br />'+
            '<button>Login</button>'
        })
        var sb = SqueezeBox.open(login,{handler: 'adopt', 'size': {x: 450, y:200} })

        login.getElements('button')[0].addEvent('click', function (){
            //try to login
            var l = login.getElements('input[name=login]')[0].value;
            var p = login.getElements('input[name=pwd]')[0].value;

            new Request({
                url: 'backend.php',
                data : 'action=login&login='+l+'&password='+p,
                onSuccess: function (text){
                    if(text=="1") {
                        evt.map.logged = true;
                        $('logininfo').set('html',"<hr />You're logged with user: "+l+"<hr />")
                        if (nextaction == "open") this._open(evt);
                        if (nextaction == "save") this._save(evt);
                    }else{
                        if(text==0) text="Please give login and password...";
                        login.getElements('p.msg')[0].set('html', text).addClass('show').addClass('error');
                    }
                }.bind(this)
            }).send();
        }.bind(this))
    },

    save: function (evt){
        evt.stop();
        this.checklogin(evt,"save");

    },
    _save: function(evt){
        new Request({
            url: 'backend.php',
            method: 'post',
            'data' : 'action=getfiles',
            onSuccess: function (text){
                var openbox = new Element('div');
                var list = new Element('div');
                list.set('html',text)
                list.injectInside(openbox);
                var other = new Element('p').set('html','Fill a new file if you wont\'t overwrite existing file:').injectInside(openbox);
                var filenameentry = new Element('input').set({
                        'name' : "newfilename"
                }).injectInside(openbox);
                var savebutton = new Element('button').set('html','Save').injectInside(openbox);

                savebutton.addEvent('click',function(){
                    var file = this.getParent().getElements('select')[0].value;
                    if (filenameentry.value!="") file = filenameentry.value
                    if (file.replace(' ','') == "") {
                        alert("Please, choose a filename");
                        return;
                    }
                   new Request({
                        url: 'backend.php',
                        method: 'post',
                        data: 'action=save&name='+file+'&xml='+evt.xml,
                        onSuccess: function (text, xml){
                            alert('File saved');
                            SqueezeBox.close()
                        }
                   }).send();
                });
                SqueezeBox.open(openbox,{handler: 'adopt'});
            }.bind(this)
        }).send()
    },

    open: function (evt){
        evt.stop();
        this.checklogin(evt,"open");
    },

    _open: function (evt){
        var _this = this;
        new Request({
            url: 'backend.php',
            method: 'post',
            'data' : 'action=getfiles',
            onSuccess: function (text){
                var openbox = new Element('div');
                var list = new Element('div');
                list.set('html',text)
                list.injectInside(openbox);
                var openbutton = new Element('button').set('html','Open').injectInside(openbox);
                var dlbutton = new Element('button').set('html','Download XML').injectInside(openbox);

                openbutton.addEvent('click',function(){
                    var file = this.getParent().getElements('select')[0].value;
                    _this.processOpen(evt,file);
                    SqueezeBox.close()
                });
                dlbutton.addEvent('click',function(){
                    var file = this.getParent().getElements('select')[0].value;
                    document.location.href="backend.php?action=getxml&filename="+file;
                    SqueezeBox.close()
                });

                SqueezeBox.open(openbox,{handler: 'adopt'});
            }.bind(this)
        }).send()
    },

    processOpen: function (evt,filename) {
        new Request({
            url: 'backend.php',
            data: 'action=getcontent&filename='+filename,
            onSuccess: function (content){
                evt.map.importxml(content);
            }.bind(this)
        }).send();
    }
});

var phpBackend = new PHPBackend();
window.addEvent('mapsave',phpBackend.save.bind(phpBackend));
window.addEvent('mapopen',phpBackend.open.bind(phpBackend));
window.addEvent('mapready',phpBackend.init.bind(phpBackend));

window.addEvent('domready',function (){
    $('save').set('html','Save');
    $('open').set('html','Open');
    var loginfo = new Element('p').set({
        'id' : 'logininfo',
        'html' : "<hr />You're not logged... try to open or save to login<hr />"
    }).injectBefore('save');

});
